import { useDebugValue, useState } from "react";

export const useCookie = (key: string, initialValue: string = '') => {

    const getCookie = () => {
        const value = document.cookie.match(`(^| )${key}=([^;]*)(;|$)`)
        console.log(value);
        return value ? value[2] : initialValue
    }

    const [cookie, setCookie] = useState(getCookie())

    const updateCookie = (newValue: string) => {
        document.cookie = `${key}=${newValue}`
        setCookie(newValue)
    }

    const deleteCookie = () => {
        // cookie 没有对应的删除方法，设置过期时间，浏览器会自动删除
        document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC`
    }
    useDebugValue(cookie)

    return [cookie, updateCookie, deleteCookie] as const

}